import Taro from '@tarojs/taro';
import apiConfig from './apiConfig'

import { camelCaseToLine } from '../utils'

//网络请求拦截器
const interceptor = function (chain) {
  chain.requestParams.isShowLoading && Taro.showLoading({
    title: '加载中',
  })

  const requestParams = chain.requestParams
  let authToken = Taro.getStorageSync('auth-token') || ''//拿到本地缓存中存的token
  let orgTag = apiConfig.orgTag//拿到本地缓存中存的token
  requestParams.header = {
    ...requestParams.header,
    'auth-token': authToken, //将token添加到头部
    'org-tag': orgTag
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const API_PREFIX = '/api/v1'
const request = async (method, url, params, showCamelCase = true) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  let newData = {
    asc_or_desc: 'DESC',
  }
  // 驼峰转下划线
  if (params) {
    for (let key in params) {
      if (key != 'isShowLoading') {
        //加上if判断去掉原型链上的
        if (showCamelCase) {
          newData[camelCaseToLine(key)] = params[key]
        } else {
          newData[key] = params[key]
        }
      }
    }
  }


  let isShowLoading = true
  if (params && "isShowLoading" in params) {
    isShowLoading = params.isShowLoading
  }


  const option = {
    method,
    isShowLoading: isShowLoading,
    url: apiConfig.baseUrl + API_PREFIX + url,
    data: newData,
    timeout: apiConfig.timeout,
    header: {
      'content-type': contentType,
    },
    success(res) {

    },
    error(e) {
      console.log('api', '请求接口出现问题', e);
    },
    complete(res) {
      let route = Taro.getStorageSync('login-route')
      let routers = Taro.getCurrentPages() //获取路由栈，最后一个为当前页面
      let currPage
      if (routers.length) {
        currPage = routers[routers.length - 1];
      }

      Taro.hideLoading(
        {
          complete() {
            if (!res.data.code || res.data.code != 200) {
              try {
                switch (res.data?.code) {
                  case 11007: //这里处理有点笨后面可以想一下怎么优化

                    if (route && route == '/login/login/index' && currPage?.route == route) {
                      throw new Error("登录已过期")
                    } else {
                      Taro.removeStorageSync('login-route')
                      setTimeout(() => {
                        Taro.reLaunch({
                          url: "/login/login/index"
                        })
                      }, 2000)
                      throw new Error("登录已过期")

                    }
                  case 500247:
                    throw new Error("请前往APP修改")
                  case 500051: //500051净值不存咋也不做弹窗处理
                    break
                  case 500050: //500050份额不存咋也不做弹窗处理
                    break
                  default:
                    throw new Error(res.data.message)

                }
              } catch (err) {
                Taro.showToast({
                  title: err.message,
                  icon: "error",
                })
              }

            }
          }
        }
      )
    }

  }


  const resp = await Taro.request(option);

  return resp.data;//根据个人需要返回
}

export default {
  get: (url, config?: Object, showCamelCase = true) => {
    return request('GET', url, config, showCamelCase);
  },
  post: (url, config?: Object, showCamelCase = true) => {
    return request('POST', url, config, showCamelCase);
  },
  put: (url, config?: Object, showCamelCase = true) => {
    return request('PUT', url, config, showCamelCase);
  },
  delete: (url, config?: Object, showCamelCase = true) => {
    return request('DELETE', url, config, showCamelCase);
  },
  patch: (url, config?: Object, showCamelCase = true) => {
    return request('PATCH', url, config, showCamelCase);
  },
}
